<template>
	<el-card class="layout-query">
		<el-form ref="queryParamsRef" :inline="true">
			<el-form-item prop="postCode" label="登录名">
				<el-input v-model="state.queryParams.loginName" placeholder="登录名"></el-input>
			</el-form-item>
			<el-form-item prop="postCode" label="用户姓名">
				<el-input v-model="state.queryParams.cnName" placeholder="用户姓名"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="handleReset">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item v-auth="'M012_A'">
				<el-button type="primary" @click="dialogState = true">新增审核用户</el-button>
			</el-form-item>
		</el-form>
		<el-table
			v-loading="state.dataListLoading"
			:data="state.dataList"
			stripe
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
		>
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="dwmc" label="单位名称" align="center" header-align="center"></el-table-column>
			<el-table-column prop="userType" label="对应业务" align="center" header-align="center">
				<template #default="scope">
					<span v-if="scope.row.userType == '1'">标准</span>
					<span v-if="scope.row.userType == '2'">前瞻性</span>
					<span v-if="scope.row.userType == '1,2'">全部</span>
				</template>
			</el-table-column>
			<el-table-column prop="roleName" label="用户类型" align="center" header-align="center"> </el-table-column>
			<el-table-column prop="cnName" label="用户姓名" align="center" header-align="center"> </el-table-column>
			<el-table-column prop="loginName" label="登录名" align="center" header-align="center"> </el-table-column>
			<!-- <el-table-column prop="" label="用户密码" align="center"> </el-table-column> -->
			<!-- <el-table-column prop="" label="手机号" align="center" header-align="center"> </el-table-column> -->
			<el-table-column prop="roleCode" label="权限编码" header-align="center" align="center"></el-table-column>
			<el-table-column prop="dwdm" label="单位编号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center"></el-table-column>
			<el-table-column prop="iflag" label="状态" align="center">
				<template #default="scope">
					<el-tag v-if="scope.row.iflag === 1" type="success">正常</el-tag>

					<el-tag v-else type="danger">注销</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="130">
				<template #default="scope">
					<!-- <el-button type="primary" link @click="userDetailHandle(false, scope.row)">详情</el-button> -->
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="userDetailHandle(false, scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="!scope.row.roleCode.includes('SB01') && !scope.row.roleCode.includes('SYADMIN')"
						v-auth="'M012_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="userEditHandle(scope.row)"
					>
						<Edit
					/></el-icon>

					<el-icon
						v-if="scope.row.iflag == 1 && scope.row.roleCode != 'SYADMIN'"
						v-auth="'M012_Z'"
						:size="16"
						color="#1491FF"
						title="注销"
						style="cursor: pointer; margin: 0 6px"
						@click="userStatusHandle(scope.row, 0)"
					>
						<Delete />
					</el-icon>
					<el-icon
						v-if="scope.row.iflag == 0"
						v-auth="'M012_Q'"
						:size="16"
						color="#1491FF"
						title="启用"
						style="cursor: pointer; margin: 0 6px"
						@click="userStatusHandle(scope.row, 1)"
					>
						<SwitchButton />
					</el-icon>
					<el-icon
						v-if="!scope.row.roleCode.includes('SB01') && !scope.row.roleCode.includes('SYADMIN')"
						:size="16"
						color="#1491FF"
						title="授权"
						style="cursor: pointer; margin: 0 6px"
						@click="userAuthHandle(scope.row)"
					>
						<Operation
					/></el-icon>
					<!-- <el-button type="success" plain small>作废</el-button> -->
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<el-pagination
			:current-page="state.queryParams.pageIndex"
			:page-size="state.queryParams.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>

		<!-- 详情 -->
		<detailDialog ref="detailDialogRef"></detailDialog>
		<cmDialog v-model="dialogState" :modal-title="formData.id == '' ? '新增' : '编辑'" model-width="600px">
			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="用户姓名" prop="cnName">
							<el-input v-model="formData.cnName" placeholder="请输入用户姓名" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="登录名" prop="loginName">
							<el-input v-model="formData.loginName" placeholder="请输入登录名" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="手机号" prop="mobile">
							<el-input v-model="formData.mobile" placeholder="请输入手机号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="用户类型" prop="yhlx">
							<el-radio-group v-model="formData.yhlx" @change="handleTypeChange">
								<el-radio v-for="(item, index) in typeList" :key="index" :value="item.code">{{ item.name }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="formData.yhlx === 'SHZG'">
					<el-col :span="formData.dwdm == 'A000010' ? 14 : 24">
						<el-form-item label="用户单位" prop="dwdm">
							<el-select v-model="formData.dwdm" placeholder="请选择用户单位" clearable>
								<el-option v-for="item in responsibleOrg" :key="item.code" :label="item.name" :value="item.code"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="formData.dwdm == 'A000010'" :span="10">
						<el-form-item prop="dwdmfj" label-width="10px">
							<el-select v-model="formData.dwdmfj" placeholder="请选择用户单位" clearable>
								<el-option v-for="item in subResponsibleOrg" :key="item.code" :label="item.name" :value="item.code"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="formData.yhlx === 'SHZZ' || formData.yhlx === 'SHZJW'">
					<el-col :span="24">
						<el-form-item label="用户单位" prop="dwdm">
							<el-input v-model="formData.dwmc" placeholder="请输入用户单位" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="formData.yhlx === 'SHZJ'">
					<el-col :span="24">
						<el-form-item label="用户单位" prop="dwmc">
							<el-input v-model="formData.dwmc" placeholder="请输入用户单位"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-foot">
					<el-button @click="dialogState = false">关闭</el-button>
					<el-button type="primary" @click="submitForm(formRef)">提交</el-button>
				</div>
			</template>
		</cmDialog>
		<cmDialog v-model="showAuthorizeDialog" modal-title="用户授权" model-width="600px">
			<el-form ref="authorizeRef" :model="authorizeForm" :rules="authorizeFormRules" label-width="100px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="用户姓名">
							{{ formData.cnName }}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="登录名">
							{{ formData.loginName }}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="手机号">
							{{ formData.mobile }}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="单位名称">
							{{ formData.dwmc }}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="用户角色" prop="role">
							<el-select v-model="authorizeForm.role" placeholder="请选择" multiple clearable>
								<el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleCode" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-foot">
					<el-button @click="showAuthorizeDialog = false">关闭</el-button>
					<el-button type="primary" @click="submitAuthForm(authorizeRef)">提交</el-button>
				</div>
			</template>
		</cmDialog>
	</el-card>
</template>
<script setup lang="ts">
import { AddUserApi, AddUserAuthApi, queryUserApi, userDetailApi, queryApi } from '@/api/system/rbac'
import cmDialog from '@/components/cm-dialog/index.vue'
import { useDictionaryStore } from '@/store/modules/dictionary'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import detailDialog from './components/detailDialog.vue'
const dictionaryStore = useDictionaryStore()
const loading = ref(false)
const state = reactive({
	queryParams: {
		loginName: '',
		cnName: '',
		pageIndex: 1,
		pageSize: 10
	},
	total: 1,
	dataListLoading: false,
	dataList: []
})
const responsibleOrg = dictionaryStore.getDictionaryByCode('T002')
const subResponsibleOrg = dictionaryStore.getDictionaryByCode('T0030')
const typeList = [
	{
		name: '主管单位',
		code: 'SHZG'
	},
	{
		name: '市场总站',
		code: 'SHZZ'
	},
	{
		name: '住建委审核人',
		code: 'SHZJW'
	},
	{
		name: '审核专家',
		code: 'SHZJ'
	}
]
const sczz = {
	name: '上海市建筑建材业市场管理总站',
	code: 'A2GLSH'
}
const zjw = {
	name: '上海市住房和城乡建设管理委员会',
	code: 'A000013'
}
const formData = ref({
	id: '',
	loginName: '',
	cnName: '',
	roleCode: '',
	rydm: '',
	dwdm: '',
	dwid: null,
	dwmc: '',
	remark: '',
	mobile: '',
	userCode: '',
	certGuid: '',
	certSn: '',
	licencesn: '',
	yhlx: 'SHZG',
	loginSource: '',
	dwdmfj: '',
	iflag: 1,
	userType: '',
	roleName: ''
})
const formRules = reactive<FormRules>({
	loginName: [{ required: true, message: '请输入登录名', trigger: 'blur' }],
	cnName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
	mobile: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
	],
	yhlx: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
	dwmc: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
	dwdm: [{ required: true, message: '请选择用户单位', trigger: 'change' }],
	dwdmfj: [{ required: true, message: '请选择用户单位', trigger: 'change' }]
})
const dialogState = ref(false)
const roleList = ref([])
// const roleList = [
// 	{
// 		name: '标准科科员',
// 		code: 'SHZZ'
// 	},
// 	{
// 		name: '主管单位',
// 		code: 'SHZG'
// 	},
// 	{
// 		name: '审核专家',
// 		code: 'SHZJ'
// 	},
// 	{
// 		name: '住建委',
// 		code: 'SHZJW'
// 	},
// 	{
// 		name: '主管单位',
// 		code: 'CKZG'
// 	}
// ]
const formRef = ref<FormInstance>()
const authorizeRef = ref<FormInstance>()
const showAuthorizeDialog = ref(false)
const authorizeForm = ref({
	role: []
})
const authorizeFormRules = reactive({
	role: [{ required: true, message: '请选择角色', trigger: 'change' }]
})

watch(
	() => dialogState.value,
	val => {
		if (!val) {
			restForm()
		}
	}
)
watch(
	() => showAuthorizeDialog.value,
	val => {
		if (!val) {
			restForm()
			authorizeForm.value = {
				role: []
			}
		}
	}
)

const restForm = () => {
	formData.value = {
		id: '',
		loginName: '',
		cnName: '',
		roleCode: '',
		rydm: '',
		dwdm: '',
		dwid: null,
		dwmc: '',
		remark: '',
		mobile: '',
		userCode: '',
		certGuid: '',
		certSn: '',
		licencesn: '',
		yhlx: 'SHZG',
		loginSource: '',
		dwdmfj: '',
		iflag: 1,
		userType: '',
		roleName: ''
	}
}

const getUserDetail = async (id: any) => {
	let queryParam = {
		id: id
	}
	await userDetailApi(queryParam).then(res => {
		formData.value = res.data
	})
}

const userEditHandle = (row: any) => {
	getUserDetail(row.id)
	dialogState.value = true
}

const userAuthHandle = async (row: any) => {
	await getUserDetail(row.id)
	showAuthorizeDialog.value = true
	if (formData.value.roleCode) {
		authorizeForm.value = {
			role: formData.value.roleCode.split(',')
		}
	}
}

const userStatusHandle = (row: any, status: number) => {
	let queryParam = {
		id: row.id
	}
	userDetailApi(queryParam).then(res => {
		formData.value = res.data
		formData.value.iflag = status
		const text = status === 1 ? '启用' : '禁用'
		ElMessageBox.confirm(`是否${text}该用户?`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				delete formData.value.roleCode
				delete formData.value.roleName
				AddUserApi(formData.value).then(res => {
					ElMessage.success('操作成功！')
					getUserList()
				})
			})
			.catch(() => {})
	})
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (formData.value.yhlx == 'SHZG') {
				responsibleOrg.forEach((item: any) => {
					if (item.code == formData.value.dwdm) {
						formData.value.dwid = item.id
						formData.value.dwmc = item.name
					}
				})
				if (formData.value.dwdm != 'A000010') {
					formData.value.dwdmfj = ''
				}
			}
			if (formData.value.yhlx == 'SHZJW' || formData.value.yhlx == 'SHZZ') {
				formData.value.dwid = ''
				formData.value.dwdmfj = ''
			}
			if (formData.value.yhlx == 'SHZJ') {
				formData.value.dwid = ''
				formData.value.dwdmfj = ''
				formData.value.dwdm = ''
			}
			delete formData.value.roleCode
			delete formData.value.roleName
			AddUserApi(formData.value).then(res => {
				ElMessage.success('操作成功！')
				dialogState.value = false
				getUserList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const submitAuthForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log(authorizeForm.value)
			let userRoleList = []
			authorizeForm.value.role.forEach((item: any) => {
				userRoleList.push({
					roleCode: item,
					remark: ''
				})
			})
			AddUserAuthApi({
				userId: formData.value.id,
				userRoleList: userRoleList
			}).then(res => {
				ElMessage.success('操作成功！')
				showAuthorizeDialog.value = false
				getUserList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const handleTypeChange = (val: string) => {
	if (val == 'SHZZ') {
		formData.value.dwmc = sczz.name
		formData.value.dwdm = sczz.code
	} else if (val == 'SHZJW') {
		formData.value.dwmc = zjw.name
		formData.value.dwdm = zjw.code
	} else {
		formData.value.dwmc = ''
		formData.value.dwdm = ''
	}
}

// 重置请求
const reset = () => {
	state.queryParams.cnName = ''
	state.queryParams.loginName = ''
	state.queryParams.pageIndex = 1
	state.queryParams.pageSize = 10
}

const handleSearch = () => {
	console.log('搜索参数:', state.queryParams)
	getUserList()
}

const handleReset = () => {
	reset()
	getUserList()
}
// 列表数据获取
const getUserList = async () => {
	state.dataListLoading = true
	await queryUserApi(state.queryParams).then(res => {
		state.dataListLoading = false
		state.dataList = res.data.list
		state.total = res.data.total
	})
}

const handleCurrentChange = (val: number) => {
	state.queryParams.pageIndex = val
	getUserList()
}
const handleSizeChange = (val: number) => {
	state.queryParams.pageSize = val
	getUserList()
}
// 详情
const detailDialogRef = ref()
const userDetailHandle = (isUpdate: Boolean, row: any) => {
	// true 新增  false 修改
	detailDialogRef.value.init(isUpdate, row)
}
onMounted(() => {
	getUserList()
	queryApi({
		roleName: '',
		roleCode: '',
		pageIndex: 1,
		pageSize: 1000
	}).then(res => {
		roleList.value = res.data.list
	})
})
</script>

<style lang="scss" scoped>
.anniu .el-form-item {
	margin-right: 10px !important;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}
</style>
